<template>
  <lay-card style="height: 100%">
    <lay-container>
      <lay-row space="10">
        <lay-col style="margin-top: 20px">
          <lay-form :model="queryForm" :pane="true">
            <lay-row space="10">
              <lay-col md="5">
                <lay-form-item label="行业" mode="inline">
                  <lay-select v-model="queryForm.industry" >
                    <lay-select-option :value="item.value" :label="item.value" v-for="item in industries"></lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col md="5">
                <lay-form-item label="市场" mode="inline">
                  <lay-select v-model="queryForm.market">
                    <lay-select-option :value="item.value" :label="item.value" v-for="item in markets"></lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col md="5">
                <lay-form-item label="协议" mode="inline">
                  <lay-select v-model="queryForm.protocol">
                    <lay-select-option :value="item.value" :label="item.value" v-for="item in protocols"></lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col md="6">
                 <lay-date-picker  v-model="rangeTime" range type="date" :placeholder="['开始日期','结束日期']"></lay-date-picker>
              </lay-col>
            </lay-row>
            <lay-row space="10">
              <lay-col md="6">
                <lay-button type="normal" size="sm" @click="queryBatFiles">查询</lay-button>
                <lay-button size="sm" @click="resetFrom">重置</lay-button>
                <lay-dropdown
                    updateAtScroll
                    :clickOutsideToClose="false"
                    ref="uploadTemplate"
                >
                  <lay-button
                      type="normal"
                      size="sm"
                      style="margin-left: 20px"
                  >上传文件</lay-button>
                  <template #content>
                    <lay-dropdown-menu>
                      <UploadFile
                        :industries="industries"
                        :markets="markets"
                        :protocols="protocols"
                        @load="queryBatFiles"
                        @cancel="uploadTemplate.hide()"
                      ></UploadFile>
                    </lay-dropdown-menu>
                  </template>
                </lay-dropdown>
              </lay-col>
            </lay-row>
          </lay-form>
        </lay-col>
      </lay-row>
      <lay-row space="20">
        <lay-col md="24">
          <lay-table
            :page="page"
            :height="'500px'"
            style="min-height: 60%"
            :columns="columns"
            :loading="loading"
            :data-source="dataSource"
            v-model:selected-keys="selectedKeys"
            @change="change"
          >
          <template v-slot:toolbar>
            <lay-row space="10">
              <lay-col md="21"><h3>行情文件</h3></lay-col>
              <lay-col md="3">
                <lay-dropdown updateAtScroll>
                  <lay-button size="xs">定时刷新({{delay}}s)</lay-button>
                  <template #content>
                      <lay-dropdown-menu>
                        <lay-dropdown-menu-item @click="startRefresh(10)">间隔10s</lay-dropdown-menu-item>
                        <lay-dropdown-menu-item @click="startRefresh(60)">间隔1min</lay-dropdown-menu-item>
                        <lay-dropdown-menu-item @click="startRefresh(300)">间隔5min</lay-dropdown-menu-item>
                      </lay-dropdown-menu>
                  </template>
                </lay-dropdown>
<!--                <lay-button size="xs" @click="stopRefresh">停止刷新</lay-button>-->
              </lay-col>
            </lay-row>
          </template>
          <template v-slot:operator="{ row }">
            <lay-button size="xs" type="normal" @click="decodeFile(row.id)">解码</lay-button>
            <lay-button size="xs" type="danger" @click="deleteRow(row)">删除</lay-button>
          </template>
        </lay-table>
        </lay-col>
      </lay-row>
    </lay-container>
  </lay-card>
</template>

<script lang="ts">
import UploadFile from "../../../components/Market/UploadFile.vue";

export default {
  name: "UploadAndUnzip",
  components: {UploadFile}
}
</script>

<script lang="ts" setup>

import {h, onBeforeUnmount, onMounted, onUnmounted, reactive, ref} from "vue";
import {clearDir, getConfig, queryUploadFiles, queryUploadFilesCount} from "../../../api/market/basic";
import {notify} from "../../../untils/tip";
import {parseFile} from "../../../api/market/market";
import {layer} from "@layui/layui-vue";

const rangeTime = ref([]);
const uploadTemplate = ref();
const loading = ref(false);
const selectedKeys = ref([]);
const page = reactive({ current: 1, limit: 10, total: 10 });

// 下拉框选择的值
const industries: any = ref([]);
const markets: any = ref([]);
const protocols: any = ref([]);

const columns = ref([
    { title:"行业", width: "5%", key:"industry", sort: "desc" },
    { title:"市场", width: "5%", key:"market"},
    { title:"协议", width: "5%", key:"protocol" },
    { title:"日期", width: "10%", key:"date", sort: "desc" },
    { title:"起始时间", width: "10%", key:"startTime", sort: "desc" },
    { title:"终止时间", width: "10%", key:"endTime", sort: "desc" },
    { title:"文件名称", width: "20%", key:"filename" },
    { title:"解析进度", width: "10%", key:"parseStatus" },
    { title:"上传时间", width: "10%", key:"joinTime", sort: "desc" },
    { title:"操作", width: "15%", customSlot:"operator", key:"operator", fixed: "right" }
]);

const dataSource = ref([]);

const timer = ref();
const delay = ref(60);

// 页面加载前查询数据
onMounted(()=>{
  queryBatFiles();
  getSelectItems('industry');
  getSelectItems('market');
  getSelectItems('protocol');
});

const queryBatFiles = () => {
  page.current = 1;
  queryFilesCount();
  loadDataSource();
}

const change = () => {
  loading.value = true;
  setTimeout(() => {
    loadDataSource();
    loading.value = false;
  }, 1000);
};

const queryForm: any = reactive({
    industry: null,
    market: null,
    protocol: null,
    startTime: null,
    endTime: null,
    current: page.current,
    limit: page.limit
});

const resetFrom = () => {
  queryForm.industry = null;
  queryForm.market = null;
  queryForm.protocol = null;
};


const getSelectItems = async (target: string) => {
  let {data, code, message} = await getConfig({target: target})
  if(code === 200){
    switch (target) {
      case 'market': markets.value = data; break;
      case 'industry': industries.value = data; break;
      case 'protocol': protocols.value = data; break;
    }
  }else {
    notify('fail', message);
  }
};

const queryFilesCount = async () => {
  if(rangeTime.value.length === 2 && rangeTime.value[0] !== ''){
    queryForm.startTime = rangeTime.value[0];
    queryForm.endTime = rangeTime.value[1];
  }
  let {data, code, message} = await queryUploadFilesCount(queryForm)
  if(code === 200){
    page.total = data;
  }else {
    notify('fail', message);
  }
};

const loadDataSource = async () => {
  dataSource.value = [];
  if(rangeTime.value.length === 2 && rangeTime.value[0] !== ''){
    queryForm.startTime = rangeTime.value[0];
    queryForm.endTime = rangeTime.value[1];
  }
  queryForm.current = (page.current - 1)*page.limit;
  queryForm.limit = page.limit;
  let {code, data, message} = await queryUploadFiles(queryForm)
  if(code === 200){
    dataSource.value = data;
  }else {
    notify('fail', message);
  }
};

const deleteRow = (row: any) => {
  layer.confirm("你确定要删除么？",
        {
            btn: [
                {text:'确定', callback: (id) => {
                    removeRow(row.id);
                    layer.close(id); }
                },
                {text:'取消', callback: (id) => {
                    layer.close(id); }
                }
            ]
        }
    );
};

const removeRow = async (rowId: any) => {
  let {code, data, message} = await clearDir({rowId: rowId})
  if(code === 200){
    await queryBatFiles();
    notify('success', message);
  }else {
    notify('fail', message);
  }
};

const decodeFile = async (rowId: any) => {
  let {code, data, message} = await parseFile({rowId: rowId})
  if(code === 200){
    startRefresh(60);
  }else {
    notify('fail', message);
  }
};

// 定时刷新任务，查询进度
const startRefresh = (number: number) => {
  delay.value = number;
  stopRefresh();
  // 停止之前的，设置新的刷新任务
  timer.value = setInterval(()=>{
    page.current = 1;
    loadDataSource();
  }, number * 1000);
  notify('success', "开始解析，并定时刷新查询进度！间隔时间：" + number.toString() + "s!");
};

// 停止定时刷新任务
const stopRefresh = () => {
  clearInterval(timer.value);
  timer.value = '';
};

// 销毁前清理定时任务
onBeforeUnmount(() => {
  stopRefresh();
})
</script>

<style scoped>
.queryForm {
  width: 25%;
  margin-right: 15px
}
</style>